#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen@163.com
@file: log_utls.py
@time: 2023/11/8 14:06
@desc: 
"""
import logging
import os
import time
from logging.handlers import TimedRotatingFileHandler

from backend.conf import config


class CustomFormatter(logging.Formatter):
    def format(self, record):
        # 获取当前时间
        current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        # 调用父类的format方法，将时间添加到日志记录中
        record.asctime = current_time
        return super().format(record)


log_dir = config.log_path  # 日志目录
if not os.path.exists(log_dir):
    os.makedirs(log_dir)

logger_obj = logging.getLogger()
logger_obj.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s]-[%(levelname)s]-[%(message)s]', "%Y-%m-%d %H:%M:%S")
file_handler = TimedRotatingFileHandler(config.log_path + config.log_file_prefix, when=config.log_rotate_when,
                                        interval=1, backupCount=config.log_rotate_backup_count)
file_handler.setFormatter(formatter)

console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)

logger_obj.addHandler(file_handler)
logger_obj.addHandler(console_handler)

Log_dict = {
    "ERROR": 40,
    "WARNING": 30,
    "INFO": 20,
    "DEBUG": 10,
}


class app_log():

    @staticmethod
    def debug(message):
        if Log_dict.get(config.log_level) >= 10:
            logger_obj.info(message)

    @staticmethod
    def info(message):
        if Log_dict.get(config.log_level) >= 20:
            logger_obj.info(message)

    @staticmethod
    def warning(message):
        if Log_dict.get(config.log_level) >= 30:
            logger_obj.info(message)

    @staticmethod
    def error(message):
        if Log_dict.get(config.log_level) >= 40:
            logger_obj.info(message)
